package com.fei.yygh.hosp.controller.api;


import com.fei.yygh.excption.YyghException;
import com.fei.yygh.helper.HttpRequestHelper;
import com.fei.yygh.hosp.service.HospitalService;
import com.fei.yygh.hosp.service.HospitalSetService;
import com.fei.yygh.model.hosp.Hospital;
import com.fei.yygh.result.Result;
import com.fei.yygh.result.ResultCodeEnum;
import com.fei.yygh.util.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/api/hosp")
public class ApiHospitalController {

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private HospitalSetService hospitalSetService;

    //上传医院接口
    @PostMapping("/saveHospital")
    public Result saveHospital(HttpServletRequest request) {
        //获取传递过来的数据
        Map<String, String[]> requestMap = request.getParameterMap();
        //用工具类将数组转换为object类型
        Map<String, Object> objectMap = HttpRequestHelper.switchMap(requestMap);
        //获取医院系统传递过来的签名，签名已经进行了MD5加密
        String sign =(String) objectMap.get("sign");

        //根据传过来的医院编号，来查询数据库获取数据中的签名
        String hoscode =(String) objectMap.get("hoscode");

        //根据医院编号查询数据库
       String key =(String) hospitalSetService.getSignKey(hoscode);

       //对图片传输过程中“+”自动转变为了空格，此处要转换回来
        String logoData =(String) objectMap.get("logoData");
        logoData = logoData.replaceAll(" ","+");//转换
        objectMap.put("logoData",logoData);//将转换完后的放回去


       //对查询到的key进行MD5加密
        String keyMD5 = MD5.encrypt(key);


        //判断，两个key值是否相等
        if(sign.equals(keyMD5)){
            //调用service方法
            hospitalService.save(objectMap);
            return Result.ok();
        }else {
            throw new YyghException(ResultCodeEnum.SIGN_ERROR);
        }

    }

    //医院查询接口
    @PostMapping ("hospital/show")
    public Result showHospital(HttpServletRequest request) {
        //获取传递过来的数据
        Map<String, String[]> requestMap = request.getParameterMap();
        //用工具类将数组转换为object类型
        Map<String, Object> objectMap = HttpRequestHelper.switchMap(requestMap);
        //获取医院系统传递过来的签名，签名已经进行了MD5加密
        String sign =(String) objectMap.get("sign");

        //根据传过来的医院编号，来查询数据库获取数据中的签名
        String hoscode =(String) objectMap.get("hoscode");

        //根据医院编号查询数据库
        String key =(String) hospitalSetService.getSignKey(hoscode);

        //key值对比
        if(!sign.equals(key)){
            throw new YyghException(ResultCodeEnum.SIGN_ERROR);
        }
        //key值验证通过
        String hospital =(String) objectMap.get("hospital");
        Hospital hospital1 = hospitalService.getByHospital(hospital);
        return Result.ok(hospital1);
    }


}
